import axios from "axios";
import { ElMessage } from "element-plus";
import { logOut } from "@/common/loginOut";
const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

instance.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  if (token) {
    if (config.headers) {
      config.headers["Authorization"] = token;
    }
  }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    const data = response.data as IResponse<any>;
    if (data.code === 401) {
      logOut(null, () => {
        ElMessage.success("token已过期，请登录");
      });
    } else if (data.code !== 200 && data.errno !== 0) {
      ElMessage.error(data.message);
    }
    return response.data;
  },
  (err) => {
    ElMessage.error("请求失败,错误信息:" + err.message);
    Promise.reject(err);
  }
);

export default instance;
